﻿using System.Text;

namespace Ndns.Packet.Text
{
    public class PunycodeEncoding : Encoding
    {
        private static PunycodeEncoding _instance = new PunycodeEncoding();
        public static PunycodeEncoding Default => _instance;
        
        public bool IsEncodingRequired(string plain)
        {
            foreach (var c in plain)
            {
                if (!Punycode.IsBasic(c))
                    return true;
            }
            return false;
        }

        public override int GetByteCount(char[] chars, int index, int count)
        {
            return PunycodeEncoder.Default.GetByteCount(chars, index, count, true);
        }

        public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
        {
            return PunycodeEncoder.Default.GetBytes(chars, charIndex, charCount, bytes, byteIndex, true);
        }

        public override int GetCharCount(byte[] bytes, int index, int count)
        {
            return PunycodeDecoder.Default.GetCharCount(bytes, index, count);
        }

        public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
        {
            return PunycodeDecoder.Default.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
        }

        public override int GetMaxByteCount(int charCount)
        {
            return charCount * 4 + 1;
        }

        public override int GetMaxCharCount(int byteCount)
        {
            return byteCount;
        }

        public override Encoder GetEncoder()
        {
            return PunycodeEncoder.Default;
        }

        public override Decoder GetDecoder()
        {
            return PunycodeDecoder.Default;
        }
        
    }

}
